const pool = require('../config/db');

class ProjectMember {
  // 添加项目成员
  static async addMember(projectId, userId, role = 'member') {
    try {
      const [result] = await pool.execute(
        'INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?)',
        [projectId, userId, role]
      );
      return result.insertId;
    } catch (error) {
      console.error('添加项目成员错误:', error);
      throw error;
    }
  }

  // 获取项目成员列表
  static async getProjectMembers(projectId) {
    try {
      const [members] = await pool.execute(
        `SELECT 
          pm.id, 
          pm.project_id, 
          pm.user_id, 
          pm.role, 
          pm.join_date, 
          pm.status,
          u.username,
          u.real_name,
          u.email
        FROM project_members pm
        JOIN users u ON pm.user_id = u.id
        WHERE pm.project_id = ?`,
        [projectId]
      );
      return members;
    } catch (error) {
      console.error('获取项目成员错误:', error);
      throw error;
    }
  }

  // 更新成员角色
  static async updateMemberRole(projectId, userId, newRole) {
    try {
      const [result] = await pool.execute(
        'UPDATE project_members SET role = ? WHERE project_id = ? AND user_id = ?',
        [newRole, projectId, userId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新成员角色错误:', error);
      throw error;
    }
  }

  // 移除项目成员
  static async removeMember(memberId){
    try {
      const [result] = await pool.execute(
        'DELETE FROM project_members WHERE id= ? ',
        [memberId]
      );
      return result.affectedRows > 0;
    } catch (error) {
      console.error('移除项目成员错误:', error);
      throw error;
    }
  }

  // 检查用户是否是项目成员
  static async isMember(projectId, userId) {
    try {
      const [members] = await pool.execute(
        'SELECT * FROM project_members WHERE project_id = ? AND user_id = ?',
        [projectId, userId]
      );
      return members.length > 0;
    } catch (error) {
      console.error('检查项目成员错误:', error);
      throw error;
    }
  }
}

module.exports = ProjectMember;
